<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小组管理 - 南宁二中2025级37班</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        
        :root {
            --primary: #1e88e5;
            --secondary: #64b5f6;
            --accent1: #e53935;
            --accent2: #43a047;
            --accent3: #fdd835;
            --accent4: #8e24aa;
            --dark: #2d3436;
            --light: #f5f6fa;
        }
        
        body {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            color: var(--dark);
            line-height: 1.6;
            min-height: 100vh;
            overflow-x: hidden;
        }
        
        .container {
            width: 90%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem 0;
        }
        
        /* 导航栏样式 */
        header {
            background: linear-gradient(90deg, var(--primary), var(--secondary), var(--accent1), var(--accent2));
            background-size: 400% 400%;
            animation: gradientShift 10s ease infinite;
            color: white;
            padding: 1rem 0;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        
        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            font-size: 1.8rem;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .logo i {
            font-size: 2rem;
        }
        
        .nav-links {
            display: flex;
            list-style: none;
        }
        
        .nav-links li {
            margin-left: 1.5rem;
            position: relative;
        }
        
        .nav-links a {
            color: white;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s;
            padding: 0.5rem 1rem;
            border-radius: 30px;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .nav-links a:hover {
            background-color: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }
        
        .nav-links a i {
            font-size: 1.1rem;
        }
        
        .user-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn-auth {
            padding: 0.6rem 1.2rem;
            border-radius: 30px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-login {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .btn-auth:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        /* 页面标题 */
        .page-header {
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
        }
        
        .page-header h1 {
            font-size: 2.5rem;
            color: var(--primary);
            margin-bottom: 0.5rem;
        }
        
        .page-header p {
            font-size: 1.2rem;
            color: #666;
            max-width: 600px;
            margin: 0 auto;
        }
        
        /* 工具栏样式 */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 1rem;
            background: white;
            padding: 1.5rem;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        
        .search-box {
            display: flex;
            align-items: center;
            background: var(--light);
            border-radius: 50px;
            padding: 0.5rem 1rem;
            width: 300px;
        }
        
        .search-box input {
            border: none;
            background: transparent;
            padding: 0.5rem;
            width: 100%;
            font-size: 1rem;
            outline: none;
        }
        
        .search-box i {
            color: #666;
        }
        
        .toolbar-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn {
            padding: 0.8rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        
        .btn-success {
            background: var(--accent2);
            color: white;
        }
        
        .btn-danger {
            background: var(--accent1);
            color: white;
        }
        
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        /* 小组卡片样式 */
        .groups-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .group-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            transition: all 0.3s;
        }
        
        .group-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
        }
        
        .group-header {
            padding: 1.5rem;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            position: relative;
        }
        
        .group-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }
        
        .group-name {
            font-size: 1.5rem;
            font-weight: bold;
        }
        
        .group-score {
            font-size: 2rem;
            font-weight: bold;
        }
        
        .group-description {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .group-body {
            padding: 1.5rem;
        }
        
        .group-stats {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }
        
        .stat {
            text-align: center;
        }
        
        .stat-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary);
        }
        
        .stat-label {
            font-size: 0.9rem;
            color: #666;
        }
        
        .group-members {
            margin-bottom: 1.5rem;
        }
        
        .members-title {
            font-weight: 600;
            margin-bottom: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .members-list {
            max-height: 200px;
            overflow-y: auto;
        }
        
        .member-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.8rem 0;
            border-bottom: 1px solid #f5f5f5;
        }
        
        .member-item:last-child {
            border-bottom: none;
        }
        
        .member-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 1rem;
        }
        
        .member-info {
            flex: 1;
        }
        
        .member-name {
            font-weight: 500;
            margin-bottom: 0.2rem;
        }
        
        .member-score {
            font-size: 0.9rem;
            color: #666;
        }
        
        .group-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .btn-small {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 0.3rem;
        }
        
        .btn-small-primary {
            background: var(--primary);
            color: white;
        }
        
        .btn-small-danger {
            background: var(--accent1);
            color: white;
        }
        
        .btn-small:hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
        }
        
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(5px);
        }
        
        .modal.active {
            display: flex;
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal-content {
            background: white;
            border-radius: 20px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
            animation: slideUp 0.4s;
        }
        
        @keyframes slideUp {
            from { transform: translateY(50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .modal-header {
            padding: 1.5rem 2rem;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            border-radius: 20px 20px 0 0;
        }
        
        .modal-title {
            font-size: 1.5rem;
            font-weight: 600;
        }
        
        .close-modal {
            background: none;
            border: none;
            font-size: 1.8rem;
            cursor: pointer;
            color: white;
            transition: transform 0.3s;
        }
        
        .close-modal:hover {
            transform: rotate(90deg);
        }
        
        .modal-body {
            padding: 2rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #555;
        }
        
        .form-group input, .form-group textarea, .form-group select {
            width: 100%;
            padding: 1rem;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .form-group input:focus, .form-group textarea:focus, .form-group select:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(30, 136, 229, 0.2);
        }
        
        .modal-footer {
            padding: 1.5rem 2rem;
            border-top: 1px solid #eee;
            text-align: center;
        }
        
        .btn-modal {
            padding: 1rem 2rem;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            width: 100%;
            font-size: 1.1rem;
        }
        
        .btn-modal-primary {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
        }
        
        .btn-modal-primary:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(30, 136, 229, 0.4);
        }
        
        /* 页脚样式 */
        footer {
            background: linear-gradient(90deg, var(--dark), #3d3d3d);
            color: white;
            text-align: center;
            padding: 2.5rem 0;
            margin-top: 3rem;
            border-radius: 20px 20px 0 0;
        }
        
        .footer-content {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .footer-section {
            flex: 1;
            min-width: 200px;
        }
        
        .footer-section h3 {
            margin-bottom: 1.5rem;
            font-size: 1.3rem;
        }
        
        .footer-links {
            list-style: none;
        }
        
        .footer-links li {
            margin-bottom: 0.8rem;
        }
        
        .footer-links a {
            color: #ddd;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .footer-links a:hover {
            color: white;
        }
        
        .copyright {
            padding-top: 1.5rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            font-size: 0.9rem;
            color: #aaa;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .navbar {
                flex-direction: column;
                gap: 1rem;
            }
            
            .nav-links {
                flex-wrap: wrap;
                justify-content: center;
            }
            
            .nav-links li {
                margin: 0.5rem;
            }
            
            .user-actions {
                margin-top: 1rem;
            }
            
            .toolbar {
                flex-direction: column;
                align-items: stretch;
            }
            
            .search-box {
                width: 100%;
            }
            
            .toolbar-actions {
                width: 100%;
                justify-content: center;
            }
            
            .groups-container {
                grid-template-columns: 1fr;
            }
            
            .footer-content {
                flex-direction: column;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <header>
        <div class="container">
            <nav class="navbar">
                <div class="logo">
                    <i class="fas fa-school"></i>
                    <span>南宁二中2025级37班</span>
                </div>
                <ul class="nav-links">
                    <li><a href="index.html"><i class="fas fa-home"></i> 首页</a></li>
                    <li><a href="student_management.html"><i class="fas fa-user-graduate"></i> 学生管理</a></li>
                    <li><a href="group_management.html" style="background-color: rgba(255, 255, 255, 0.3);"><i class="fas fa-users"></i> 小组管理</a></li>
                    <li><a href="leaderboard.html"><i class="fas fa-trophy"></i> 排行榜</a></li>
                </ul>
                <div class="user-actions">
                    <button class="btn-auth btn-login" id="login-btn">
                        <i class="fas fa-sign-in-alt"></i> 教师登录
                    </button>
                </div>
            </nav>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1>小组管理</h1>
            <p>管理班级小组，查看小组详情，分配学生到小组</p>
        </div>
        
        <!-- 工具栏 -->
        <div class="toolbar">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="search-input" placeholder="搜索小组名称...">
            </div>
            <div class="toolbar-actions">
                <button class="btn btn-primary" id="add-group-btn">
                    <i class="fas fa-plus"></i> 添加小组
                </button>
                <button class="btn btn-success" id="auto-assign-btn">
                    <i class="fas fa-random"></i> 自动分配
                </button>
            </div>
        </div>
        
        <!-- 小组列表 -->
        <div class="groups-container" id="groups-container">
            <!-- 小组数据将通过JavaScript动态加载 -->
        </div>
    </main>

    <!-- 添加小组模态框 -->
    <div class="modal" id="add-group-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加小组</h3>
                <button class="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="add-group-form">
                    <div class="form-group">
                        <label for="group-name">小组名称</label>
                        <input type="text" id="group-name" placeholder="请输入小组名称" required>
                    </div>
                    <div class="form-group">
                        <label for="group-description">小组描述</label>
                        <textarea id="group-description" placeholder="请输入小组描述（可选）" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-modal-primary" id="submit-add-group">添加小组</button>
            </div>
        </div>
    </div>

    <!-- 编辑小组模态框 -->
    <div class="modal" id="edit-group-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">编辑小组</h3>
                <button class="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="edit-group-form">
                    <input type="hidden" id="edit-group-id">
                    <div class="form-group">
                        <label for="edit-group-name">小组名称</label>
                        <input type="text" id="edit-group-name" placeholder="请输入小组名称" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-group-description">小组描述</label>
                        <textarea id="edit-group-description" placeholder="请输入小组描述（可选）" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-modal-primary" id="submit-edit-group">保存修改</button>
            </div>
        </div>
    </div>

    <!-- 小组详情模态框 -->
    <div class="modal" id="group-detail-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">小组详情</h3>
                <button class="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="group-header" id="detail-group-header">
                    <div class="group-title">
                        <div class="group-name" id="detail-group-name">第一组</div>
                        <div class="group-score" id="detail-group-score">285</div>
                    </div>
                    <div class="group-description" id="detail-group-description">学习小组</div>
                </div>
                
                <div class="group-body">
                    <div class="group-stats">
                        <div class="stat">
                            <div class="stat-value" id="detail-member-count">5</div>
                            <div class="stat-label">成员数量</div>
                        </div>
                        <div class="stat">
                            <div class="stat-value" id="detail-avg-score">57</div>
                            <div class="stat-label">平均分</div>
                        </div>
                        <div class="stat">
                            <div class="stat-value" id="detail-rank">1</div>
                            <div class="stat-label">排名</div>
                        </div>
                    </div>
                    
                    <div class="group-members">
                        <div class="members-title">
                            <span>小组成员</span>
                            <button class="btn-small btn-small-primary" id="manage-members-btn">
                                <i class="fas fa-user-edit"></i> 管理成员
                            </button>
                        </div>
                        <div class="members-list" id="detail-members-list">
                            <!-- 成员列表将通过JavaScript动态加载 -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-modal-primary" id="close-detail-modal">关闭</button>
            </div>
        </div>
    </div>

    <!-- 管理成员模态框 -->
    <div class="modal" id="manage-members-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">管理小组成员</h3>
                <button class="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="toolbar" style="margin-bottom: 1.5rem;">
                    <div class="search-box">
                        <i class="fas fa-search"></i>
                        <input type="text" id="member-search-input" placeholder="搜索学生...">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="available-students">可分配的学生</label>
                    <select id="available-students" size="5" style="height: 150px;">
                        <!-- 学生选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                
                <div style="display: flex; justify-content: center; gap: 1rem; margin: 1.5rem 0;">
                    <button class="btn btn-primary" id="add-member-btn">
                        <i class="fas fa-arrow-right"></i> 添加到小组
                    </button>
                    <button class="btn btn-danger" id="remove-member-btn">
                        <i class="fas fa-arrow-left"></i> 从小组移除
                    </button>
                </div>
                
                <div class="form-group">
                    <label for="current-members">当前小组成员</label>
                    <select id="current-members" size="5" style="height: 150px;">
                        <!-- 当前成员将通过JavaScript动态加载 -->
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-modal-primary" id="save-members">保存成员设置</button>
            </div>
        </div>
    </div>

    <!-- 登录模态框 -->
    <div class="modal" id="login-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">教师登录</h3>
                <button class="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="login-form">
                    <div class="form-group">
                        <label for="login-username">用户名</label>
                        <input type="text" id="login-username" placeholder="请输入教师用户名" required>
                    </div>
                    <div class="form-group">
                        <label for="login-password">密码</label>
                        <input type="password" id="login-password" placeholder="请输入密码" required>
                    </div>
                    <div class="form-options">
                        <div class="remember-me">
                            <input type="checkbox" id="remember-me">
                            <label for="remember-me">记住我</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn-modal btn-modal-primary" id="submit-login">登录</button>
                <div class="switch-form" style="margin-top: 1.5rem; text-align: center; color: #666;">
                    注意：只有教师账号可以登录进行操作
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer>
        <div class="container">
            <div class="footer-content">
                <div class="footer-section">
                    <h3>关于我们</h3>
                    <p>南宁二中2025级37班班级优化系统，致力于提升班级管理效率和学习积极性。</p>
                </div>
                <div class="footer-section">
                    <h3>快速链接</h3>
                    <ul class="footer-links">
                        <li><a href="index.html">首页</a></li>
                        <li><a href="student_management.html">学生管理</a></li>
                        <li><a href="group_management.html">小组管理</a></li>
                        <li><a href="leaderboard.html">排行榜</a></li>
                    </ul>
                </div>
                <div class="footer-section">
                    <h3>联系我们</h3>
                    <p>南宁市第二中学</p>
                    <p>2025级37班</p>
                </div>
            </div>
            <div class="copyright">
                <p>© 2023 南宁二中2025级37班 - 班级优化大师 | 所有权利保留</p>
            </div>
        </div>
    </footer>

    <script>
        // 修复URL解析问题 - 使用固定服务器地址
        const API_BASE_URL = 'http://localhost:5000';

        console.log('🌐 API基础URL:', API_BASE_URL);

        // 全局变量
        let groups = [];
        let students = [];
        let currentGroup = null;
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', async function() {
            // 检查登录状态
            checkLoginStatus();
            
            // 绑定事件
            bindEvents();
            
            // 从后端加载数据
            await loadDataFromBackend();
        });
        
        // 从后端加载数据
        async function loadDataFromBackend() {
            try {
                showLoadingState();
                
                console.log('正在从后端加载数据...');
                
                // 测试后端连接
                const testResponse = await fetch(API_BASE_URL + '/health');
                if (!testResponse.ok) {
                    throw new Error('后端服务器未响应');
                }
                
                // 并行加载所有数据
                const [groupsResponse, studentsResponse] = await Promise.all([
                    fetch(API_BASE_URL + '/api/groups').catch(e => { throw new Error('小组数据加载失败: ' + e.message) }),
                    fetch(API_BASE_URL + '/api/students').catch(e => { throw new Error('学生数据加载失败: ' + e.message) })
                ]);

                if (!groupsResponse.ok) throw new Error('小组数据响应错误: ' + groupsResponse.status);
                if (!studentsResponse.ok) throw new Error('学生数据响应错误: ' + studentsResponse.status);

                const groupsData = await groupsResponse.json();
                const studentsData = await studentsResponse.json();

                if (!groupsData.success) throw new Error('小组数据API错误: ' + groupsData.message);
                if (!studentsData.success) throw new Error('学生数据API错误: ' + studentsData.message);

                groups = groupsData.groups || [];
                students = studentsData.students || [];

                console.log('✅ 从后端加载数据成功:', {
                    groups: groups.length,
                    students: students.length
                });

                // 渲染小组列表
                renderGroups(groups);
                
                showConnectionStatus('✅ 后端连接正常', 'success');
                
            } catch (error) {
                console.error('❌ 从后端加载数据失败:', error);
                showConnectionStatus('❌ 后端连接失败: ' + error.message, 'error');
                
                // 使用模拟数据作为后备
                await loadMockData();
            }
        }
        
        // 加载模拟数据
        async function loadMockData() {
            console.log('使用模拟数据模式');
            
            students = [
                { id: 1, name: "李小明", total_score: 95, group_id: 1, student_id: "S001" },
                { id: 2, name: "张伟", total_score: 88, group_id: 2, student_id: "S002" },
                { id: 3, name: "王芳", total_score: 92, group_id: 1, student_id: "S003" },
                { id: 4, name: "刘洋", total_score: 78, group_id: 3, student_id: "S004" },
                { id: 5, name: "陈静", total_score: 85, group_id: 2, student_id: "S005" },
                { id: 6, name: "杨帆", total_score: 90, group_id: 4, student_id: "S006" },
                { id: 7, name: "黄磊", total_score: 82, group_id: 3, student_id: "S007" },
                { id: 8, name: "周涛", total_score: 96, group_id: 1, student_id: "S008" },
                { id: 9, name: "吴倩", total_score: 89, group_id: 5, student_id: "S009" },
                { id: 10, name: "郑华", total_score: 91, group_id: 4, student_id: "S010" }
            ];
            
            groups = [
                { 
                    id: 1, 
                    name: "第一组", 
                    description: "学习小组", 
                    total_score: 283,
                    students: students.filter(s => s.group_id === 1)
                },
                { 
                    id: 2, 
                    name: "第二组", 
                    description: "创新小组", 
                    total_score: 173,
                    students: students.filter(s => s.group_id === 2)
                },
                { 
                    id: 3, 
                    name: "第三组", 
                    description: "进步小组", 
                    total_score: 160,
                    students: students.filter(s => s.group_id === 3)
                },
                { 
                    id: 4, 
                    name: "第四组", 
                    description: "精英小组", 
                    total_score: 181,
                    students: students.filter(s => s.group_id === 4)
                },
                { 
                    id: 5, 
                    name: "第五组", 
                    description: "奋进小组", 
                    total_score: 89,
                    students: students.filter(s => s.group_id === 5)
                },
                { 
                    id: 6, 
                    name: "第六组", 
                    description: "超越小组", 
                    total_score: 0,
                    students: []
                }
            ];
            
            renderGroups(groups);
        }
        
        // 显示加载状态
        function showLoadingState() {
            const groupsContainer = document.getElementById('groups-container');
            groupsContainer.innerHTML = `
                <div style="grid-column: 1 / -1; text-align: center; padding: 3rem;">
                    <i class="fas fa-spinner fa-spin" style="font-size: 3rem; color: var(--primary); margin-bottom: 1rem;"></i>
                    <p>正在从服务器加载数据...</p>
                </div>
            `;
        }
        
        // 渲染小组列表
        function renderGroups(groupsList) {
            const groupsContainer = document.getElementById('groups-container');
            groupsContainer.innerHTML = '';
            
            if (groupsList.length === 0) {
                groupsContainer.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 3rem;">
                        <i class="fas fa-users-slash" style="font-size: 3rem; color: #ccc; margin-bottom: 1rem;"></i>
                        <p>没有找到小组数据</p>
                        <button class="btn btn-primary" onclick="loadDataFromBackend()" style="margin-top: 1rem;">
                            <i class="fas fa-refresh"></i> 重新加载
                        </button>
                    </div>
                `;
                return;
            }
            
            // 按总分排序
            const sortedGroups = [...groupsList].sort((a, b) => b.total_score - a.total_score);
            
            sortedGroups.forEach((group, index) => {
                const groupCard = document.createElement('div');
                groupCard.className = 'group-card';
                
                // 计算平均分
                const avgScore = group.students && group.students.length > 0 
                    ? Math.round(group.total_score / group.students.length) 
                    : 0;
                
                groupCard.innerHTML = `
                    <div class="group-header">
                        <div class="group-title">
                            <div class="group-name">${group.name}</div>
                            <div class="group-score">${group.total_score}</div>
                        </div>
                        <div class="group-description">${group.description || '暂无描述'}</div>
                    </div>
                    <div class="group-body">
                        <div class="group-stats">
                            <div class="stat">
                                <div class="stat-value">${group.students ? group.students.length : 0}</div>
                                <div class="stat-label">成员数量</div>
                            </div>
                            <div class="stat">
                                <div class="stat-value">${avgScore}</div>
                                <div class="stat-label">平均分</div>
                            </div>
                            <div class="stat">
                                <div class="stat-value">${index + 1}</div>
                                <div class="stat-label">排名</div>
                            </div>
                        </div>
                        
                        <div class="group-members">
                            <div class="members-title">
                                <span>小组成员</span>
                            </div>
                            <div class="members-list">
                                ${group.students && group.students.length > 0 
                                    ? group.students.slice(0, 3).map(student => `
                                        <div class="member-item">
                                            <div class="member-avatar">${student.name.charAt(0)}</div>
                                            <div class="member-info">
                                                <div class="member-name">${student.name}</div>
                                                <div class="member-score">${student.total_score} 分</div>
                                            </div>
                                        </div>
                                    `).join('')
                                    : '<div style="text-align: center; padding: 1rem; color: #999;">暂无成员</div>'
                                }
                                ${group.students && group.students.length > 3 
                                    ? `<div style="text-align: center; padding: 0.5rem; color: var(--primary);">还有 ${group.students.length - 3} 名成员...</div>` 
                                    : ''
                                }
                            </div>
                        </div>
                        
                        <div class="group-actions">
                            <button class="btn-small btn-small-primary view-group-btn" data-id="${group.id}">
                                <i class="fas fa-eye"></i> 查看详情
                            </button>
                            <button class="btn-small btn-small-primary edit-group-btn" data-id="${group.id}">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="btn-small btn-small-danger delete-group-btn" data-id="${group.id}">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    </div>
                `;
                
                groupsContainer.appendChild(groupCard);
            });
            
            // 绑定小组操作按钮事件
            bindGroupActions();
        }
        
        // 绑定小组操作按钮事件
        function bindGroupActions() {
            // 查看详情按钮
            document.querySelectorAll('.view-group-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const groupId = parseInt(this.getAttribute('data-id'));
                    const group = groups.find(g => g.id === groupId);
                    if (group) {
                        openGroupDetailModal(group);
                    }
                });
            });
            
            // 编辑按钮
            document.querySelectorAll('.edit-group-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const groupId = parseInt(this.getAttribute('data-id'));
                    const group = groups.find(g => g.id === groupId);
                    if (group) {
                        openEditGroupModal(group);
                    }
                });
            });
            
            // 删除按钮
            document.querySelectorAll('.delete-group-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const groupId = parseInt(this.getAttribute('data-id'));
                    const group = groups.find(g => g.id === groupId);
                    if (group) {
                        deleteGroup(group);
                    }
                });
            });
        }
        
        // 打开小组详情模态框
        function openGroupDetailModal(group) {
            currentGroup = group;
            
            // 更新模态框内容
            document.getElementById('detail-group-name').textContent = group.name;
            document.getElementById('detail-group-score').textContent = group.total_score;
            document.getElementById('detail-group-description').textContent = group.description || '暂无描述';
            
            // 计算统计数据
            const memberCount = group.students ? group.students.length : 0;
            const avgScore = memberCount > 0 ? Math.round(group.total_score / memberCount) : 0;
            const rank = groups.filter(g => g.total_score > group.total_score).length + 1;
            
            document.getElementById('detail-member-count').textContent = memberCount;
            document.getElementById('detail-avg-score').textContent = avgScore;
            document.getElementById('detail-rank').textContent = rank;
            
            // 渲染成员列表
            const membersList = document.getElementById('detail-members-list');
            membersList.innerHTML = '';
            
            if (group.students && group.students.length > 0) {
                group.students.forEach(student => {
                    const memberItem = document.createElement('div');
                    memberItem.className = 'member-item';
                    memberItem.innerHTML = `
                        <div class="member-avatar">${student.name.charAt(0)}</div>
                        <div class="member-info">
                            <div class="member-name">${student.name}</div>
                            <div class="member-score">${student.total_score} 分</div>
                        </div>
                    `;
                    membersList.appendChild(memberItem);
                });
            } else {
                membersList.innerHTML = '<div style="text-align: center; padding: 2rem; color: #999;">暂无成员</div>';
            }
            
            // 打开模态框
            document.getElementById('group-detail-modal').classList.add('active');
        }
        
        // 打开编辑小组模态框
        function openEditGroupModal(group) {
            currentGroup = group;
            
            // 填充表单数据
            document.getElementById('edit-group-id').value = group.id;
            document.getElementById('edit-group-name').value = group.name;
            document.getElementById('edit-group-description').value = group.description || '';
            
            // 打开模态框
            document.getElementById('edit-group-modal').classList.add('active');
        }
        
        // 创建小组
        async function handleCreateGroup(groupData) {
            try {
                console.log('创建小组:', groupData);
                
                const response = await fetch(API_BASE_URL + '/api/groups', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(groupData)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '创建失败');
                }
                
                const result = await response.json();
                
                if (result.success) {
                    // 重新加载小组数据
                    await loadDataFromBackend();
                    return result.group;
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('创建小组失败:', error);
                throw error;
            }
        }
        
        // 更新小组
        async function handleUpdateGroup(groupId, groupData) {
            try {
                console.log('更新小组:', groupId, groupData);
                
                const response = await fetch(API_BASE_URL + `/api/groups/${groupId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(groupData)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '更新失败');
                }
                
                const result = await response.json();
                
                if (result.success) {
                    // 重新加载小组数据
                    await loadDataFromBackend();
                    return result.group;
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('更新小组失败:', error);
                throw error;
            }
        }
        
        // 删除小组
        async function deleteGroup(group) {
            if (!confirm(`确定要删除小组 "${group.name}" 吗？此操作无法撤销。`)) {
                return;
            }
            
            try {
                console.log('删除小组:', group.id);
                
                const response = await fetch(API_BASE_URL + `/api/groups/${group.id}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '删除失败');
                }
                
                const result = await response.json();
                
                if (result.success) {
                    // 重新加载小组数据
                    await loadDataFromBackend();
                    alert('小组删除成功！');
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('删除小组失败:', error);
                alert('删除小组失败: ' + error.message);
            }
        }
        
        // 自动分配学生到小组
        async function handleAutoAssign() {
            if (!confirm('确定要自动分配所有学生到小组吗？此操作将重置当前的分组。')) {
                return;
            }
            
            try {
                console.log('自动分配学生到小组');
                
                const response = await fetch(API_BASE_URL + '/api/groups/auto_assign', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '自动分配失败');
                }
                
                const result = await response.json();
                
                if (result.success) {
                    // 重新加载数据
                    await loadDataFromBackend();
                    alert('自动分配成功！');
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('自动分配失败:', error);
                alert('自动分配失败: ' + error.message);
            }
        }
        
        // 绑定事件
        function bindEvents() {
            // 模态框控制
            const modals = {
                addGroup: document.getElementById('add-group-modal'),
                editGroup: document.getElementById('edit-group-modal'),
                groupDetail: document.getElementById('group-detail-modal'),
                manageMembers: document.getElementById('manage-members-modal'),
                login: document.getElementById('login-modal')
            };
            
            // 打开模态框
            document.getElementById('add-group-btn').addEventListener('click', () => {
                modals.addGroup.classList.add('active');
            });
            
            document.getElementById('auto-assign-btn').addEventListener('click', () => {
                handleAutoAssign();
            });
            
            document.getElementById('manage-members-btn').addEventListener('click', () => {
                openManageMembersModal();
            });
            
            document.getElementById('login-btn').addEventListener('click', () => {
                modals.login.classList.add('active');
            });
            
            // 关闭模态框
            function closeModals() {
                Object.values(modals).forEach(modal => {
                    modal.classList.remove('active');
                });
            }
            
            document.querySelectorAll('.close-modal').forEach(btn => {
                btn.addEventListener('click', closeModals);
            });
            
            document.getElementById('close-detail-modal').addEventListener('click', closeModals);
            
            window.addEventListener('click', function(e) {
                if (Object.values(modals).some(modal => e.target === modal)) {
                    closeModals();
                }
            });
            
            // 添加小组
            document.getElementById('submit-add-group').addEventListener('click', async function() {
                const name = document.getElementById('group-name').value;
                const description = document.getElementById('group-description').value;
                
                if (!name) {
                    alert('请填写小组名称！');
                    return;
                }
                
                const button = this;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 添加中...';
                button.disabled = true;
                
                try {
                    await handleCreateGroup({
                        name: name,
                        description: description
                    });
                    
                    closeModals();
                    document.getElementById('add-group-form').reset();
                    alert(`成功添加小组: ${name}`);
                } catch (error) {
                    alert('添加小组失败: ' + error.message);
                } finally {
                    button.innerHTML = '添加小组';
                    button.disabled = false;
                }
            });
            
            // 编辑小组
            document.getElementById('submit-edit-group').addEventListener('click', async function() {
                const id = document.getElementById('edit-group-id').value;
                const name = document.getElementById('edit-group-name').value;
                const description = document.getElementById('edit-group-description').value;
                
                if (!name) {
                    alert('请填写小组名称！');
                    return;
                }
                
                const button = this;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
                button.disabled = true;
                
                try {
                    await handleUpdateGroup(parseInt(id), {
                        name: name,
                        description: description
                    });
                    
                    closeModals();
                    alert(`小组信息更新成功！`);
                } catch (error) {
                    alert('更新小组失败: ' + error.message);
                } finally {
                    button.innerHTML = '保存修改';
                    button.disabled = false;
                }
            });
            
            // 搜索功能
            document.getElementById('search-input').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const filteredGroups = groups.filter(group => 
                    group.name.toLowerCase().includes(searchTerm) ||
                    (group.description && group.description.toLowerCase().includes(searchTerm))
                );
                renderGroups(filteredGroups);
            });
            
            // 登录功能
            document.getElementById('submit-login').addEventListener('click', async function() {
                const username = document.getElementById('login-username').value;
                const password = document.getElementById('login-password').value;
                
                if (!username || !password) {
                    alert('请填写用户名和密码！');
                    return;
                }
                
                const button = this;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 登录中...';
                button.disabled = true;
                
                try {
                    const response = await fetch(API_BASE_URL + '/api/teacher_login', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ username, password })
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        alert('🎉 登录成功！');
                        closeModals();
                        updateTeacherInterface(result.teacher);
                    } else {
                        alert('登录失败: ' + result.message);
                    }
                } catch (error) {
                    alert('登录失败: ' + error.message);
                } finally {
                    button.innerHTML = '登录';
                    button.disabled = false;
                }
            });
        }
        
        // 打开管理成员模态框
        function openManageMembersModal() {
            if (!currentGroup) return;
            
            // 填充可分配学生列表
            const availableStudentsSelect = document.getElementById('available-students');
            availableStudentsSelect.innerHTML = '';
            
            const unassignedStudents = students.filter(student => 
                !student.group_id || student.group_id === null
            );
            
            unassignedStudents.forEach(student => {
                const option = document.createElement('option');
                option.value = student.id;
                option.textContent = `${student.name} (${student.total_score}分)`;
                availableStudentsSelect.appendChild(option);
            });
            
            // 填充当前成员列表
            const currentMembersSelect = document.getElementById('current-members');
            currentMembersSelect.innerHTML = '';
            
            if (currentGroup.students && currentGroup.students.length > 0) {
                currentGroup.students.forEach(student => {
                    const option = document.createElement('option');
                    option.value = student.id;
                    option.textContent = `${student.name} (${student.total_score}分)`;
                    currentMembersSelect.appendChild(option);
                });
            }
            
            // 打开模态框
            document.getElementById('manage-members-modal').classList.add('active');
        }
        
        // 更新教师界面
        function updateTeacherInterface(user) {
            document.querySelector('.user-actions').innerHTML = `
                <div class="user-info" style="display: flex; align-items: center; gap: 1rem;">
                    <div style="width: 32px; height: 32px; border-radius: 50%; background: var(--primary); display: flex; align-items: center; justify-content: center; color: white; font-weight: bold;">
                        ${user.username.charAt(0).toUpperCase()}
                    </div>
                    <span style="color: white; font-weight: 500;">${user.username} 老师</span>
                    <button class="btn-auth btn-login" id="logout-btn" style="background: rgba(255,255,255,0.2);">
                        <i class="fas fa-sign-out-alt"></i> 退出
                    </button>
                </div>
            `;
            
            document.getElementById('logout-btn').addEventListener('click', function() {
                if (confirm('确定要退出登录吗？')) {
                    document.querySelector('.user-actions').innerHTML = `
                        <button class="btn-auth btn-login" id="login-btn">
                            <i class="fas fa-sign-in-alt"></i> 教师登录
                        </button>
                    `;
                    document.getElementById('login-btn').addEventListener('click', function() {
                        document.getElementById('login-modal').classList.add('active');
                    });
                    alert('已退出登录');
                }
            });
        }
        
        // 检查登录状态
        function checkLoginStatus() {
            // 简化版登录状态检查
            const teacherData = localStorage.getItem('teacher_data');
            if (teacherData) {
                try {
                    const teacher = JSON.parse(teacherData);
                    updateTeacherInterface(teacher);
                } catch (e) {
                    console.error('读取教师信息失败:', e);
                }
            }
        }
        
        // 显示连接状态
        function showConnectionStatus(message, type) {
            const existingStatus = document.getElementById('connection-status');
            if (existingStatus) {
                existingStatus.remove();
            }
            
            const statusEl = document.createElement('div');
            statusEl.id = 'connection-status';
            statusEl.innerHTML = `
                <div style="
                    position: fixed;
                    bottom: 20px;
                    right: 20px;
                    padding: 10px 15px;
                    border-radius: 8px;
                    background: ${type === 'success' ? '#4CAF50' : type === 'warning' ? '#FF9800' : '#f44336'};
                    color: white;
                    font-size: 14px;
                    z-index: 1000;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
                ">
                    <i class="fas ${type === 'success' ? 'fa-check' : type === 'warning' ? 'fa-exclamation-triangle' : 'fa-exclamation-circle'}"></i>
                    ${message}
                </div>
            `;
            
            document.body.appendChild(statusEl);
            
            setTimeout(() => {
                if (statusEl.parentNode) {
                    statusEl.remove();
                }
            }, 5000);
        }
        
        // 添加重新加载函数到全局作用域
        window.loadDataFromBackend = loadDataFromBackend;
    </script>
</body>
</html>